package com.king.radar;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.king.view.radarview.RadarView;
import com.mumu.dialog.MMLoading;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author acer
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivityApp";
    RadarView rv;

    Button btnStyle, btnRadar, btnScore;

    TextView tvScan, tvMaliceApp;

    private boolean isAll;
    private MMLoading mmLoading;
    private Thread thread;
    private List<String> mAppList = new ArrayList<>();
    private List<String> mMaliceAppList = new ArrayList<>();
    private List<String> mCheckedMaliceAppList = new ArrayList<>();
    private Map<String, Boolean> mapMalice = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv = (RadarView) findViewById(R.id.rv);
        tvScan = (TextView) findViewById(R.id.tvScan);
        tvMaliceApp = (TextView) findViewById(R.id.tvMaliceApp);

        btnStyle = (Button) findViewById(R.id.btnStyle);
        btnRadar = (Button) findViewById(R.id.btnRadar);
        btnScore = (Button) findViewById(R.id.btnScore);

        btnStyle.setOnClickListener(this);
        btnRadar.setOnClickListener(this);
        btnScore.setOnClickListener(this);

        MMLoading.Builder builder = new MMLoading.Builder(this)
                .setMessage("加载中...")
                .setCancelable(false)
                .setCancelOutside(false);
        mmLoading = builder.create();
        loadApps();
    }

    private void loadApps() {
        mmLoading.show();
        mAppList.clear();
        mMaliceAppList.clear();

        mMaliceAppList.add("bannerSample");
        mMaliceAppList.add("手机不克隆");
        mMaliceAppList.add("图库");
        mMaliceAppList.add("平安乡镇");
        mMaliceAppList.add("天翼186");
        mMaliceAppList.add("校园拳击手");
        mMaliceAppList.add("LibChecker");
        mMaliceAppList.add("萤石云视频");

        for (String s : mMaliceAppList) {
            if (!mapMalice.containsKey(s)) {
                mapMalice.put(s, Boolean.FALSE);
            }
        }

        PackageManager pm = getPackageManager();
        // 查询所有已经安装的应用程序  MATCH_UNINSTALLED_PACKAGES代表已删除，但还有安装目录的
        List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        // 通过getPackageManager()的queryIntentActivities方法遍历,得到所有能打开的app的packageName
        List<ResolveInfo> resolveinfoList = getPackageManager()
                .queryIntentActivities(resolveIntent, 0);
        Set<String> allowPackages = new HashSet();
        for (ResolveInfo resolveInfo : resolveinfoList) {
            allowPackages.add(resolveInfo.activityInfo.packageName);
        }
        for (ApplicationInfo app : appInfos) {
            if (allowPackages.contains(app.packageName)) {
                mAppList.add(app.loadLabel(pm).toString());
//                Log.e(TAG, "onCreate: " + app.loadLabel(pm).toString());
            }
        }
        mmLoading.dismiss();
    }

    private void clickStyle() {
        if (isAll) {
            rv.setScanColor(new int[]{Color.TRANSPARENT, Color.TRANSPARENT, rv.getCircleColor()});
        } else {
            rv.setScanColor(new int[]{Color.TRANSPARENT, rv.getCircleColor()});
        }
        isAll = !isAll;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String s = msg.obj.toString();
                tvScan.setText("正在检测" + s + "等"
                        + mAppList.size() + "个应用...");
            } else if (msg.what == 1) {
                String s = msg.obj.toString();
                tvScan.setText(s + "等" + mAppList.size() + "个应用检测完毕");
                tvMaliceApp.setVisibility(View.VISIBLE);
                if (mCheckedMaliceAppList.size() == 0) {
                    rv.showScore(100f);
                    tvMaliceApp.setText("未检测到恶意程序");
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("发现"+mCheckedMaliceAppList.size()+"个疑似恶意程序：");
                    for (String s1 : mCheckedMaliceAppList) {
                        sb.append(s1);
                        sb.append(",");
                    }
                    tvMaliceApp.setText(sb.toString());
                    rv.showScore(100f - mCheckedMaliceAppList.size());
                }
            }
        }
    };

    private void queryFilterAppInfo() {
        tvMaliceApp.setVisibility(View.GONE);
        tvMaliceApp.setText("--");
        mCheckedMaliceAppList.clear();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < mAppList.size(); i++) {
                    String s = mAppList.get(i);
                    Message ms = new Message();
                    ms.what = 0;
                    ms.obj = s;
                    handler.sendMessage(ms);
                    if (mapMalice.containsKey(s)) {
                        mCheckedMaliceAppList.add(s);
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if ((i + 1) == mAppList.size()) {
                        Message ms1 = new Message();
                        ms1.what = 1;
                        ms1.obj = s;
                        handler.sendMessage(ms1);
                    }
                }
            }
        });
        thread.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStyle:
                clickStyle();
                break;
            case R.id.btnRadar:
                rv.start();
                queryFilterAppInfo();
                break;
            case R.id.btnScore:
                rv.showScore(98f);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        thread.stop();
    }

    /**
     * 样例程序
     *
     * @param arr1
     * @param arr2
     */
    private String[] intersect(String[] arr1, String[] arr2) {

        String str1 = "产品:业务:流程:注册:审核";
        String str2 = "业务:签订:流程:录入:产品";
        String[] split1 = str1.split(":");
        String[] split2 = str2.split(":");
        String[] intersect = intersect(split1, split2);
        for (String str : intersect) {
            Log.e(TAG, "onCreate: " + str);
        }

        Map<String, Boolean> map = new HashMap<>();
        LinkedList<String> list = new LinkedList<>();
        //第一组数据全部设置为False
        for (String str : arr1) {
            if (!map.containsKey(str)) {
                map.put(str, Boolean.FALSE);
            }
        }
        //第二组数据中含有第一组的设置为True
        for (String str : arr2) {
            if (map.containsKey(str)) {
                map.put(str, Boolean.TRUE);
            }
        }
        for (Map.Entry<String, Boolean> e : map.entrySet()) {
            if (e.getValue().equals(Boolean.TRUE)) {
                list.add(e.getKey());
            }
        }
        String[] result = {};
        return list.toArray(result);
    }

}
